from math import *
from pyglet.window import key
import pyglet
from map import Map
import data
import ui
from particles import *

class Game(object):
    def __init__(self):
        self.win = pyglet.window.Window(800,600)
        self.win.push_handlers(self)
        self.fps = pyglet.clock.ClockDisplay()
        self.game_start = False 
        self.game_pause = False
        self.player = pyglet.media.Player()
        data.loadData()
        self.player.queue(data.bgrnd_sound)
        self.player.eos_action = self.player.EOS_LOOP
        self.player.play()
        self.world = Map() 
        wp = self.world.pos
        hp = self.world.hero.pos
        self.start_xy =(wp[0]+hp[0], wp[1]+hp[1]) 
        self.final_xy= wp
        self.emiters = (Blast((240,450), data.pickup_image.id), Blast((560,450), data.pickup_image.id))
        pyglet.clock.schedule_interval(self.tick, 1/60.0)
        pyglet.app.run()
    
    def tick(self, dt):
        if self.game_start and not self.game_pause:
            self.world.update(dt)
            wp = self.world.pos
            hp = self.world.hero.pos
            self.start_xy =(wp[0]+hp[0], wp[1]+hp[1]) 
        else:
            for emiter in self.emiters:
                emiter.update(dt)

    def on_draw(self):
        if self.game_start:
            self.win.clear()
            self.world.render() 
            self.world.drawGuide(self.start_xy, self.final_xy)
            if self.game_pause:
                ui.drawPauseMenu()
        else:
            self.win.clear()
            ui.drawMenu()
            glEnable(GL_TEXTURE_2D)
            for emiter in self.emiters:
                emiter.render()
            #glDisable(GL_TEXTURE_2D)
        self.fps.draw()


    def on_mouse_motion(self, x, y, dx, dy):
        if self.game_start:
            self.final_xy = (x,y)

    def on_key_press(self, symbol, modifiers):
        print "hello"
        if symbol == key.ESCAPE:
            if self.game_start and self.game_pause:
                self.world.medals.save()
            elif self.game_start:
                print "paused"
                self.game_pause = True
                return pyglet.event.EVENT_HANDLED

    def on_mouse_press(self, x, y, button, modifiers):
        if self.game_start:
            if self.game_pause:
                self.game_pause = False
            else:
                wp = self.world.pos
                (vx, vy) = (self.final_xy[0]-self.start_xy[0], self.final_xy[1]-self.start_xy[1])
                vel = (vx/sqrt(vx*vx+vy*vy), vy/sqrt(vx*vx+vy*vy)) 
                self.world.setHeroVel(vel)
        else:
            self.game_start = True

